<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:realtimeTask:add']"
        >新增</el-button>
      </el-col>
      
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:realtimeTask:remove']"
        >删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="realtimeTaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label="摄像头位置">
                <span>{{ scope.row.ipcPosition }}</span>
            </el-form-item>
            <el-form-item label="进度">
              <span>{{ scope.row.progress }}</span>
            </el-form-item>
            <el-form-item label="开始时间">
                <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </el-form-item>
            <el-form-item label="结束时间">
                <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </el-form-item>
            <el-form-item label="主码流">
               <span>{{ scope.row.mainStreamUrl }}</span>
            </el-form-item>
            <el-form-item label="子码流">
              <span>{{ scope.row.subStreamUrl }}</span>
            </el-form-item>
            <el-form-item label="视频流状态">
              <dict-tag :options="dict.type.sys_stream_status" :value="scope.row.mainStreamStatus"/>
            </el-form-item>
            
            <el-form-item label="终端名称">
                <span>{{ scope.row.terminalName }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="任务ID" align="center" prop="taskId" v-if="true"/>
      <el-table-column label="任务名称" align="center" prop="name" />
      <el-table-column label="摄像头名称" align="center" prop="ipcName" />
      <el-table-column label="是否定时任务" align="center" prop="isTimePlan">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isTimePlan"/>
        </template>
      </el-table-column>
       
      <el-table-column label="算法状态" align="center" prop="channelStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_channel_status" :value="scope.row.channelStatus"/>
        </template>
      </el-table-column>

      <el-table-column label="任务状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_task_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-show = "scope.row.isTimePlan=='N' && scope.row.status=='0'"
            size="mini"
            type="text"
            icon="el-icon-switch-button"
            @click="handleStartTask(scope.row)"
            v-hasPermi="['system:realtimeTask:edit']"
          >启动</el-button>

          <el-button
            v-show = "scope.row.isTimePlan=='N' && scope.row.status=='1'"
            size="mini"
            type="text"
            icon="el-icon-switch-button"
            @click="handleStopTask(scope.row)"
            v-hasPermi="['system:realtimeTask:edit']"
          >停止</el-button>
          <el-button
          v-show = "scope.row.status=='0'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:realtimeTask:remove']"
          >删除</el-button>
          <el-button
              size="small"
              type="text"
              icon="el-icon-video-camera"
              @click="handleReviewVideo(scope.row)"
              v-hasPermi="['system:offlineTask:edit']"
            >播放</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改实时任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="摄像头名称" prop="ipcName">
          <el-input v-model="form.ipcName" placeholder="请输入摄像头名称" />
        </el-form-item>
        <el-form-item label="摄像头位置" prop="ipcPosition">
          <el-input v-model="form.ipcPosition" placeholder="请输入摄像头位置" />
        </el-form-item>
        <el-form-item label="主码流" prop="mainStreamUrl">
          <el-input v-model="form.mainStreamUrl" placeholder="请输入主码流" />
        </el-form-item>
        <el-form-item label="子码流" prop="subStreamUrl">
          <el-input v-model="form.subStreamUrl" placeholder="请输入子码流" />
        </el-form-item>
        <el-form-item label="是否定时任务" required>
          <el-radio-group v-model="form.isTimePlan">
            <el-radio
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="任务时间" prop="startEndTime" v-show="isTimePlan">
          <el-date-picker
            v-model="form.startEndTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            align="right">
          </el-date-picker>
        </el-form-item>

        <!-- <el-form-item label="开始时间" prop="startTime" v-show="isTimePlan">
          <el-date-picker clearable
            v-model="form.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime"  v-show="isTimePlan">
          <el-date-picker clearable
            v-model="form.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="选择终端" required>
          <el-select v-model="form.terminalId"  placeholder="请选择终端" @change="handleTerminalSelectChange" >
            <el-option
              v-for="item in terminalOptions"
              :key="item.terminalId"
              :label="item.terminalName"
              :value="item.terminalId"
            ></el-option>
          </el-select>
        </el-form-item>
         
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog 
      title="视频" 
      :visible.sync="openVideoPlay"  
      width="60%" height="60%"   
      center style="margin-top: 0px; text-align: center;" 
      @close="closeVideoDialog" 
      append-to-body
      >
        <video id="video" muted="muted" ref="cameraVideo" width="100%" height="80%" style="background-color: #000;  object-fit: contain"></video>
    </el-dialog>

  </div>
</template>

<script>
import { listRealtimeTask, getRealtimeTask, delRealtimeTask, addRealtimeTask, updateRealtimeTask,startRealtimeTask,stopRealtimeTask } from "@/api/system/realtimeTask";
import { listTerminal, getTerminal } from "@/api/system/terminal";

export default {
  name: "RealtimeTask",
  dicts: ['sys_stream_status', 'sys_task_status', 'sys_yes_no','sys_channel_status'],
  data() {
    return {
      //webrtc插件
      webRtcServer: null,
      //是否弹窗播放
      openVideoPlay: false,

      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      //算法终端列表
      terminalOptions:[],

      // 实时任务表格数据
      realtimeTaskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        ipcName: undefined,
        ipcPosition: undefined,
        startTime: undefined,
        endTime: undefined,
        status: undefined,
        deptId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskId: [
          { required: true, message: "任务ID不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        ipcName: [
          { required: true, message: "摄像头名称不能为空", trigger: "blur" }
        ],
        ipcPosition: [
          { required: true, message: "摄像头位置不能为空", trigger: "blur" }
        ],
        mainStreamUrl: [
          { required: true, message: "主码流不能为空", trigger: "blur" }
        ],
        subStreamUrl: [
          { required: true, message: "子码流不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getTerminal();
  },

  computed:{
    isTimePlan:function(){
      return this.form.isTimePlan=='Y'?true:false;
    },
    
    operationType: function(row){
      if(row.status=='0'){
        return "启动"
      }else if(row.status=='1'){
        return "停止"
      }else if(row.status=='2'){
        return "结束"
      }else if(row.status=='3'){
        return "终止"
      }
    }
  },

  methods: {
    /**查询主板列表*/
    getTerminal(){
      this.loading=true;
      let optionQueryParams={deptId:this.$store.getters.deptId}
      
      listTerminal(optionQueryParams).then(response=>{
          this.terminalOptions = response.rows;
          //console.log(this.terminalOptions)
          this.loading=false;
        });
    },

    /** 查询实时任务列表 */
    getList() {
      this.loading = true;
      this.queryParams.deptId = this.$store.getters.deptId;
      listRealtimeTask(this.queryParams).then(response => {
        this.realtimeTaskList = response.rows;
        console.log("real time task:",this.realtimeTaskList)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        taskId: undefined,
        name: undefined,
        ipcName: undefined,
        ipcPosition: undefined,
        mainStreamUrl: undefined,
        subStreamUrl: undefined,
        mainStreamStatus: 0,
        isTimePlan: "N",
        startEndTime: [],
        startTime: undefined,
        endTime: undefined,
        progress: 0,
        channelStatus: 0,
        status: "0",
        terminalId: undefined,
        terminalName: undefined,
        deptId: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    handleTerminalSelectChange(terminalId){
      for(let i=0;i<this.terminalOptions.length;i++){
        if(this.terminalOptions[i].terminalId == terminalId){
          this.form.terminalName =this.terminalOptions[i].terminalName;
          break;
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实时任务";
    },

    /** 启动任务操作 */
    handleStartTask(row) {
      this.loading = true;
      const taskId = row.taskId || this.ids
      startRealtimeTask(taskId).then(response => {
        console.log(response)
        const code = response.code
        const msg = response.msg
        if(code!=200){
          Message({
            message: msg,
            type: 'error'
          })
        }
        this.loading = false;
        this.getList()
        setTimeout(() => {
          this.getList()
        }, 3000);
      });
    },

    /** 停止任务操作 */
    handleStopTask(row) {
      this.loading = true;
      const taskId = row.taskId || this.ids
      stopRealtimeTask(taskId).then(response => {
        this.loading = false;
        this.getList()
        setTimeout(() => {
          this.getList()
        }, 3000);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //console.log(this.form.startTime)
          this.form.deptId = this.$store.getters.deptId;
          //计划任务，提取开始结束时间
          if(this.form.isTimePlan=='Y'){
            this.form.startTime = this.form.startEndTime[0];
            this.form.endTime = this.form.startEndTime[1];
          }

          this.buttonLoading = true;
          if (this.form.taskId != null) {
            updateRealtimeTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addRealtimeTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids;
      this.$modal.confirm('是否确认删除实时任务编号为"' + taskIds + '"的数据项？').then(() => {
        this.loading = true;
        return delRealtimeTask(taskIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/realtimeTask/export', {
        ...this.queryParams
      }, `realtimeTask_${new Date().getTime()}.xlsx`)
    },

    /** 播放视频操作 */
    handleReviewVideo(row) {
      this.openVideoPlay = true;

      //需要查看的rtsp地址
      //this.webRtcServer.connect('rtsp://admin:123456@192.168.31.152:554/h264/ch1/sub/av_stream')
      //this.webRtcServer.connect('rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4')
      //this.webRtcServer.connect('rtsp://192.168.2.140:8554/live/room')
      //rtsp://admin:2788@5126@192.168.2.64:554/h264/ch1/main/av_stream

      setTimeout(()=> {
        let ip = location.host.split(':')
        let serverAddr ='http://' + ip[0] +':8000' 
        if(process.env.NODE_ENV == 'development'){
          serverAddr = process.env.VUE_WEBRTC_SERVER
        }
        
        console.log("rtc server:"+serverAddr)
        this.webRtcServer = new WebRtcStreamer('video', serverAddr)
        //this.webRtcServer.connect(row.mainStreamUrl)
        this.webRtcServer.connect(row.subStreamUrl)
        this.$refs.cameraVideo.play()
      }, 1500);
       
    },

    closeVideoDialog(){
      console.log("close video dialog")
      this.webRtcServer.disconnect()
      this.$refs.cameraVideo.pause()
    },
  }
};
</script>
